<?php
class UserTask extends Model {
	private $uid, $task, $score, $exp;
	private $s = false;
	
	public function __construct($uid, $task) {
		$this->uid = $uid;
		$this->task = $task;
		$sql = 'SELECT * FROM `user_tasks` WHERE `uid` = :uid AND `task` = :task';
		$this->query($sql, array('uid' => $uid, 'task' => $task));
		if ($this->hasRows()) {
			$row = $this->getRow();
			$this->score = $row['score'];
			$this->exp = $row['exp'];
		} else $this->s = true;
	}
	
	public function update_score($score, $exp) {
		$new_s = max($score, $this->score);
		$new_e = max($exp, $this->exp);
		
		$a = Auth::getAuth();
		
		if ($new_s > $this->score) {
			$user = new UserDataObject($this->uid);
			$user->score += $new_s - $this->score;
			$user->exp   += $new_e - $this->exp;
			$user->update();
		}
		$sql = '';
		if ($this->s) {
			$sql = 'INSERT INTO `user_tasks` VALUES(:uid,:task,:score,:exp)';
		} else {
			$sql = 'UPDATE `user_tasks` SET `score` = :score AND `exp` = :exp WHERE `uid` = :uid AND `task` = :task';
		}
		$this->query($sql, array('score' => $score, 'exp' => $exp, 'uid' => $this->uid, 'task' => $this->task));
	}
}
